package com.jvm.oom.test.web.controller;


import cn.hutool.core.util.RandomUtil;
import com.jvm.oom.test.model.ModelObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 对象生成
 *
 * @author likeguo
 */
@Slf4j
@RestController
@RequestMapping("/object")
@RequiredArgsConstructor
public class ObjectBuilderController {

    /**
     * 容器
     */
    private final List<Object> container = new CopyOnWriteArrayList<>();

    /**
     * 随机对象生成
     *
     * @return success or fail
     */
    @RequestMapping("/create/random")
    public ResponseEntity<String> createByRandom() {
        ModelObject object = new ModelObject();
        if (RandomUtil.getRandom().nextInt(100) > 50) {
            container.add(object);

        }
        return ResponseEntity.ok("success");
    }

    /**
     * 随机生成对象，加限额
     *
     * @param limit limit
     * @return success or fail
     */
    @RequestMapping("/create/random/limit/{limit:1000}")
    public ResponseEntity<String> createByRandomLimit(@PathVariable("limit") Integer limit) {
        if (container.size() >= limit) {
            log.warn("随机添加：超出限额【{}】", limit);
            return ResponseEntity.ok("超出限额");
        }
        return createByRandom();
    }

    /**
     * 随机对象生成
     *
     * @return success or fail
     */
    @RequestMapping("/create/big/random")
    public ResponseEntity<String> createBigByRandom() {
        ModelObject bytes = ModelObject.bigObject();
        if (RandomUtil.getRandom().nextInt(100) > 50) {
            container.add(bytes);
            log.info("随机添加：添加成功");
        }
        return ResponseEntity.ok("success");
    }

    /**
     * 对象生成
     *
     * @return success or fail
     */
    @RequestMapping("/create/new")
    public ResponseEntity<String> createNew() {
        container.add(new ModelObject());
        log.info("确定添加：添加成功");
        return ResponseEntity.ok("success");
    }

    /**
     * 查看
     *
     * @return data list
     */
    @RequestMapping("/show/all")
    public ResponseEntity<List<Object>> show() {
        return ResponseEntity.ok(container);
    }

    /**
     * 统计
     *
     * @return data list size
     */
    @RequestMapping("/show/count")
    public ResponseEntity<Integer> count() {
        return ResponseEntity.ok(container.size());
    }



}
